from sqlalchemy import Column, BigInteger, String, SmallInteger, Integer, DateTime, Index
from app.config.database import Base
from datetime import datetime
from pydantic import BaseModel, ConfigDict
from typing import Optional

class Class(Base):
    __tablename__ = "edu_class"
    
    id = Column(BigInteger, primary_key=True, autoincrement=True, comment="班级ID")
    class_code = Column(String(20), nullable=False, unique=True, comment="班级编码（如：20250101）")
    class_name = Column(String(50), nullable=False, comment="班级名称（如：一年级一班）")
    academic_year_id = Column(BigInteger, nullable=False, comment="学年ID")
    grade = Column(SmallInteger, nullable=False, comment="年级：1-一年级 2-二年级 3-三年级 4-四年级 5-五年级")
    class_no = Column(SmallInteger, nullable=False, comment="班级序号：1-10")
    classroom_id = Column(BigInteger, comment="教室ID")
    head_teacher_id = Column(BigInteger, comment="班主任ID")
    student_count = Column(Integer, nullable=False, default=0, comment="学生人数")
    status = Column(SmallInteger, nullable=False, default=1, comment="状态：0-解散 1-正常")
    create_time = Column(DateTime, default=datetime.utcnow, nullable=False, comment="创建时间")
    update_time = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, comment="更新时间")
    
    # 索引
    __table_args__ = (
        Index('uk_class_code', 'class_code'),
        Index('idx_academic_year', 'academic_year_id'),
        Index('idx_grade_class', 'grade', 'class_no'),
        Index('idx_head_teacher', 'head_teacher_id')
    )

class ClassInDB(BaseModel):
    id: int
    class_code: str
    class_name: str
    academic_year_id: int
    grade: int
    class_no: int
    classroom_id: Optional[int] = None
    head_teacher_id: Optional[int] = None
    student_count: int = 0
    status: int = 1
    create_time: Optional[datetime] = None
    update_time: Optional[datetime] = None

    model_config = ConfigDict(from_attributes=True)